<script setup lang="ts">
import { ref, watch } from 'vue';
import type { DialogProps } from './types';

const modelValue = defineModel<boolean>({
  default: false
});
watch(modelValue, newVal => {
  isVisible.value = newVal;
});

const props = withDefaults(defineProps<DialogProps>(), {
  title: '提示',
  cancelText: '取消',
  confirmText: '确定',
  closeCallback: () => {}
});

const isVisible = ref<boolean>(modelValue.value);

const onCancelHandler = () => {
  props?.cancelHandler?.();

  close();
};
const onConfirmHandler = () => {
  props?.confirmHandler?.();

  close();
};

const close = () => {
  isVisible.value = false;

  props?.closeCallback();
};

defineOptions({ name: 'MDialog' });
</script>

<template>
  <div>
    <Transition name="modal">
      <div
        class="fixed top-0 left-0 z-40 h-screen w-screen bg-zinc-900/80"
        v-if="isVisible"
      ></div>
    </Transition>
    <Transition name="up-2-down">
      <div
        class="fixed top-[10%] left-[50%] z-50 max-h-[80%] max-w-[80%] translate-x-[-50%] cursor-pointer overflow-auto rounded border bg-white px-2 py-1.5 xl:min-w-[35%] dark:border-zinc-600 dark:bg-zinc-800"
        v-if="isVisible"
      >
        <div
          v-if="props.title"
          class="mb-2 text-lg font-bold text-zinc-900 dark:text-zinc-200"
        >
          {{ props.title }}
        </div>
        <div class="mb-2 text-base text-zinc-900 dark:text-zinc-200">
          <slot />
        </div>
        <div
          class="flex justify-end"
          v-if="props.cancelHandler || props.confirmHandler"
        >
          <MButton type="info" @click="onCancelHandler">
            {{ props.cancelText }}
          </MButton>
          <MButton type="primary" @click="onConfirmHandler" class="ml-2">
            {{ props.confirmText }}
          </MButton>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style lang="css" scoped>
@import '../styles/common/modal.css';
@import '../styles/common/up-2-down.css';
</style>
